#region LicenseHeader

// Copyright 2012 The Trustees of Indiana University.  All rights reserved.
// 
// The Indiana University licenses this file to you under the Apache License, 
// Version 2.0 (the "License"); you may not use this file except in compliance 
// with the License.  You may obtain a copy of the License at 
// 
// http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software 
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
//  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
// See the License for the specific language governing permissions and 
// limitations under the License.
// 
// @author Thilina Gunarathne (tgunarat@indiana.edu)

#endregion

#region

using System;
using System.Collections;

#endregion

namespace NAligner.Utils
{
    /// <summary>
    ///   Comparator to sort the scoring matrices by their names.
    /// </summary>
    public class AlphanumericComparator : IComparer
    {
        #region IComparer Members

        public virtual int Compare(object o1, object o2)
        {
            string s1 = (string) o1;
            string s2 = (string) o2;

            int index1 = FirstDigitIndex(s1);
            int index2 = FirstDigitIndex(s2);

            if (index1 == -1 || index2 == -1)
            {
                return string.Compare(s1, s2, true);
            }
            else
            {
                string s3 = s1.Substring(0, (index1) - (0));
                string s4 = s2.Substring(0, (index2) - (0));

                if (s3.ToUpper().Equals(s4.ToUpper()))
                {
                    return Int32.Parse(s1.Substring(index1)).CompareTo(Int32.Parse(s2.Substring(index2)));
                }
                else
                {
                    return string.Compare(s1, s2, true);
                }
            }
        }

        #endregion

        /// <summary>
        ///   Returns the index of the first digit in a String. If there are no digits, returns -1.
        /// </summary>
        private int FirstDigitIndex(string s)
        {
            for (int i = 0; i < s.Length; i++)
            {
                if (s[i] >= '0' && s[i] <= '9')
                {
                    return i;
                }
            }
            return -1;
        }
    }
}